package com.example.ui;

import java.io.Serializable;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

import com.example.downloadmanager.DownloadInfo;
import com.example.downloadmanager.Downloader;
import com.example.huashangapp.HSApplication;
import com.example.huashangapp.MyMoveView;
import com.example.net.Communication;
import com.example.net.NetRequest;
import com.example.service.MainService;
import com.example.ui.contact.MsgState;
import com.example.ui.contact.chat.L;
import com.example.ui.contact.chat.PushMessageReceiver;
import com.example.ui.contact.chat.PushMessageReceiver.EventHandler;
import com.example.ui.contact.chat.SharePreferenceUtil;
import com.example.ui.homepage.HomePageView;
import com.example.ui.homepage.MyInformationActivity;
import com.example.ui.learn.DownUtils;
import com.example.ui.learn.ListAdapter;
import com.example.ui.learn.ListeningActivity;
import com.example.ui.leftmenu.Item01View;
import com.example.ui.leftmenu.Item02View;
import com.example.ui.leftmenu.Item03View;
import com.example.ui.leftmenu.Item04View;
import com.example.ui.leftmenu.Item05View;
import com.example.ui.leftmenu.Item06View;
import com.example.ui.leftmenu.Item07View;
import com.example.ui.leftmenu.Item08View;
import com.example.ui.leftmenu.Item09View;
import com.example.ui.leftmenu.Itme10View;
import com.example.ui.leftmenu.LeftMenuView;
import com.example.util.Tools;

@SuppressWarnings("serial")
public class MainActivity extends Activity implements EventHandler,Serializable{

	public HSApplication hsApplication;
	private  Context context;
	private MyMoveView moveView;
	public LeftMenuView leftMenuView; 
	public HomePageView homePageView;
	public Item01View item01View;  
	public Item02View item02View;
	public Item03View item03View;
	public Item04View item04View;
	public Item05View item05View;
	public Item06View item06View;
	public Item07View item07View;
	public Item08View item08View;
	public Item09View item09View;
	public Itme10View item10View;
	public static String headPath;
	//private String myId;
	private Intent mainService;
	public SharedPreferences sp;
	private static MyMoveView moveView2;

	private String type = "0";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		hsApplication = (HSApplication) getApplication();
		this.context = this;
	//myId=MainService.userData.getUserId().toString();
		LoadMsgNum();
		//创建移动视图
		moveView = new MyMoveView(context);
		moveView2=moveView;
		//创建左边菜单视图
		leftMenuView = new LeftMenuView(this, moveView);
		/**主界面**************************************************/
		homePageView = new HomePageView(context,hsApplication);
		homePageView.setMyMoveView(moveView);//赋值移动视图  
		homePageView.init();
		/***************************************************/
		item01View = new Item01View(context);
		item02View = new Item02View(context,this, leftMenuView);
		item03View = new Item03View(context,hsApplication);
		item04View = new Item04View(context,hsApplication);
		item05View = new Item05View(context,hsApplication); //,hsApplication
		item06View = new Item06View(context,hsApplication);//,hsApplication
		item07View = new Item07View(context,hsApplication);
		item08View = new Item08View(context,hsApplication);
		item09View = new Item09View(context,hsApplication);
		item10View = new Itme10View(context,hsApplication);
		DownUtils.adapter = new ListAdapter(this.context,DownUtils.downUrl);
		//移动视图默认界面：界面01，
		moveView.setMainView(homePageView, leftMenuView, 0);
		moveView.getLeft_show_view().setCurrentTab(0);
		setContentView(moveView);
		if(this.item01View.view==null){
			leftMenuView.canScroll=1;
			this.item01View.setMyMoveView(moveView);
			this.item01View.init();
		}
		moveView.setMainView(item01View, this.leftMenuView, 1);
		moveView.getLeft_show_view().setCurrentTab(1);
		setContentView(moveView);
		Intent intent = new Intent(context, MyInformationActivity.class);
		headPath=HSApplication.sp.getString("imgHead","").toString();
		intent.putExtra("headPath",headPath);
		intent.putExtra("myId",HSApplication.sp.getString("userid","").toString());
		context.startActivity(intent);
	}
	

	@Override
	protected void onDestroy() {
		SaveMsgNum();		
		try {
			// 将txtOverlay删除。     
//			Item08View.txtOverlay.setVisibility(View.INVISIBLE);     
//			Item08View.windowManager.removeView(Item08View.txtOverlay); 
		} catch (Exception e) {
			
			finish();
			e.printStackTrace();
		}
		
		super.onDestroy();
	}
	@Override
	protected void onRestart() {
		super.onRestart();
		Bundle b=this.getIntent().getExtras();
		if(b!=null){
			setIntent(new Intent());
			Log.i("msg", "重启Activity"+b.getInt("moveView"));
			int item_id=b.getInt("moveView");
		if(item_id==10){
			
			if(this.item10View.view==null){
				
				this.item10View.setMyMoveView(moveView);
			}
			this.item10View.init();
			DownUtils.adapter = new ListAdapter(this.context,DownUtils.downUrl);
			moveView.setMainView(item10View, this.leftMenuView, 10);
			moveView.getLeft_show_view().setCurrentTab(10);
			setContentView(moveView);
			}
		}
		
	}
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
	}


	/**
     * 返回健
     */
    @Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
         if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
        	 if(moveView.getNowState()==MyMoveView.MAIN){
     			moveView.moveToLeft(true);
     			return true;
        	 }else{
        		 new AlertDialog.Builder(context).setTitle("提示！")
        		 .setMessage("您确定要退出吗?")
        		 .setNegativeButton("取消", null)
        		 .setPositiveButton("确定", new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						new Thread(puase).start();
						finish();
						//System.exit(0);
					}
				}).create().show();
        	 }
         }
         return false;
         //return super.onKeyDown(keyCode, event);
     }

	Runnable puase = new Runnable() {
		@Override
		public void run() {
			for (Downloader downer : DownUtils.downloaders.values()) {
				String downUrl=downer.urlstr;
				
				for (int i = 0; i <downer.infos.size(); i++) {
					DownUtils.listDownItem.get(downUrl).pause();
					DownloadInfo dinfo=(DownloadInfo) downer.infos.get(i);
					downer.dao.updataInfos(dinfo.getThreadId(), dinfo.getCompeleteSize(), dinfo.getUrl());
				}
			}if(DownUtils.downloaders.size()>0){
				Downloader.dao.closeDb();
			}
			SaveMsgNum();
			Intent intent = new Intent("com.huashang.mp3_service");
			if(HSApplication.HSlistInfo.getListen_uri()!=null&&!"".equals(HSApplication.HSlistInfo.getListen_uri())){
				intent= new Intent();
				intent.putExtra("uri",HSApplication.HSlistInfo.getListen_uri().toString());
				intent.putExtra("musicId", HSApplication.HSlistInfo.getListen_id());
				intent.putExtra("mode", Tools.STOP);
				MainService.myBinder.startMp3Service(intent);
			}
		}
	};
    
    @Override
    protected void onPause() {
    	super.onPause();
    	PushMessageReceiver.ehList.remove(this);                   //移除监听
    	PushMessageReceiver.ehList_Recent.remove(this);            //移除监听
    	PushMessageReceiver.ehList_Friend.remove(this);            //移除监听
    	PushMessageReceiver.ehList_Fd_List.remove(this);             //移除监听
    }
    @Override
    protected void onResume() {
    	super.onResume();
		//leftMenuView.adapter.notifyDataSetChanged();
		//if(item07View.my_adapter!=null)
		//item07View.my_adapter.notifyDataSetChanged();	
		
    	//PushMessageReceiver.ehList.add(Item07View.userTab);// 监听推送的消息
    	//PushMessageReceiver.ehList_Friend.add(Item07View.articeTab);// 监听推送的消息
    	//PushMessageReceiver.ehList_Chat.add(Item07View.feedTab);// 监听推送的消息
    	
		//		    	PushMessageReceiver.ehList_Notice.remove(this);// 监听推送的消息
		//		    	PushMessageReceiver.ehList_Me.remove(this);// 监听推送的消息
		//		    	PushMessageReceiver.ehList_Funs.remove(this);// 监听推送的消息
		//		    	PushMessageReceiver.ehList_Comment.remove(this);// 监听推送的消息
		//		    	PushMessageReceiver.ehList_Friend.remove(this);// 监听推送的消息
		 
		PushMessageReceiver.ehList.add(this);         //     
    	PushMessageReceiver.ehList_Recent.add(this);  //添加私信消息列表监听
    	PushMessageReceiver.ehList_Friend.add(this);  //添加好友请求消息监听	
    	PushMessageReceiver.ehList_Fd_List.add(this);   //添加好友列表消息监听
    	
    }

	/**
	 * 加载消息数目
	 */
    public void LoadMsgNum(){

    	SharePreferenceUtil mSpUtil =HSApplication.getInstance().getSpUtil();
    	PushMessageReceiver.MSG_ME = mSpUtil.getMSG_ME();
    	PushMessageReceiver.MSG_COMMENT = mSpUtil.getMSG_COMMENT();
    	PushMessageReceiver.MSG_FUNS = mSpUtil.getMSG_FUNS();
    	PushMessageReceiver.MSG_NOTICE = mSpUtil.getMSG_NOTICE();
    	PushMessageReceiver.MSG_FRIEND = mSpUtil.getMSG_FRIEND();
    	PushMessageReceiver.MSG_CHAT = mSpUtil.getMSG_CHAT();
    }
    
	/**
	 * 保存推送消息相关数目
	 */
    public void SaveMsgNum(){

    	SharePreferenceUtil mSpUtil =HSApplication.getInstance().getSpUtil();
    	mSpUtil.setMSG_COMMENT(PushMessageReceiver.MSG_ME);
    	mSpUtil.setMSG_COMMENT(PushMessageReceiver.MSG_COMMENT);
    	mSpUtil.setMSG_FUNS(PushMessageReceiver.MSG_FUNS);
    	mSpUtil.setMSG_NOTICE(PushMessageReceiver.MSG_NOTICE);
    	mSpUtil.setMSG_FRIEND(PushMessageReceiver.MSG_FRIEND);
    	mSpUtil.setMSG_CHAT(PushMessageReceiver.MSG_CHAT);
		mSpUtil.setLogin(false);
    }
    
	@SuppressWarnings("static-access")
	@Override
	public void onMessage(String message) {

		L.Debug("MSG_ME", ""+PushMessageReceiver.MSG_ME);
		L.Debug("MSG_COMMENT", ""+PushMessageReceiver.MSG_COMMENT);
		L.Debug("MSG_FUNS", ""+PushMessageReceiver.MSG_FUNS);
		L.Debug("MSG_TOTAL 2", ""+PushMessageReceiver.MSG_TOTAL);
		switch(MsgState.state){
		case MsgState.REQUEST_MSG_STATE:
			L.Debug("msg REQUEST_MSG_STATE type 1", "");
			String MeContent;
			try {
				MeContent = new JSONObject(message.toString()).getString("friendmsg");
				L.Debug("REQUEST_MSG_STATE MeContent", MeContent);
				JSONObject json = new JSONObject(MeContent);
				type = json.getString("type");
				L.Debug("REQUEST_MSG_STATE type", type);
			} catch (JSONException e) {
				e.printStackTrace();
				L.Debug("MainActivity REQUEST_MSG_STATE", e.getMessage());
			}
			
            if(type.equals("1")){//请求添加好友推送--初始化好友请求
    			item07View.initRequestMsgData();            	
            }


			break;
		case MsgState.RECENT_MSG_STATE:
			item07View.initRencentMsgData();
			break;
		case MsgState.NOTICE_MSG_STATE:
			break;
		case MsgState.ME_MSG_STATE:
			break;
		case MsgState.FUNS_MSG_STATE:
			break;
		case MsgState.COMMENT_MSG_STATE:
			break;
		case MsgState.CHAT_MSG_STATE:
			break;
		case MsgState.FD_LIST_MSG_STATE:
            //if(type.equals("2")){//学友列表添加学友           	
            //}  
			L.Debug("msg REQUEST_MSG_STATE type 2", "");
			L.Debug("push state", "MsgState.FD_LIST_MSG_STATE");
            item08View.Update_Study_List();  //message
			
			//adapter.notifyDataSetChanged();
			break;
			
		case MsgState.MAIN_MSG_STATE:			
			break;			
		}
		
		if(leftMenuView != null){
			leftMenuView.adapter.notifyDataSetChanged();
			leftMenuView.mExpandableListView.invalidate();
			leftMenuView.refreshView();			
		}

		if(item07View!=null){
			if(item07View.my_adapter!=null)
			item07View.my_adapter.notifyDataSetChanged();
			if(item07View.meNum!=null)
				item07View.meNum.setText(""+(PushMessageReceiver.MSG_NOTICE+PushMessageReceiver.MSG_ME
						+PushMessageReceiver.MSG_COMMENT+PushMessageReceiver.MSG_FUNS));
			if(item07View.friendNum!=null)
				item07View.friendNum.setText(""+PushMessageReceiver.MSG_FRIEND);
			if(item07View.chatNum!=null)
				item07View.chatNum.setText(""+PushMessageReceiver.MSG_CHAT);	
			item07View.refreshView();
			L.Debug("MainActivity", "item07View.refreshView run");
		}
		moveView.invalidate();
		



	}

	@Override
	public void onBind(String method, int errorCode, String content) {
		
	}

	@Override
	public void onNotify(String title, String content) {
		
	}

	@Override
	public void onNetChange(boolean isNetConnected) {
		
	}	
	public static  MyMoveView getMainActivityContext(){
		
		return moveView2;
	}
	

}
